package edu.ynu.se.xiecheng.achitectureclass.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class CameraService {

    private static final String CAPTURE_URL = "https://open.ys7.com/api/lapp/device/capture";

    // 固定的摄像头参数
    private static final String DEVICE_SERIAL = "L29334649";  // 固定设备序列号
    private static final int CHANNEL_NO = 1;  // 固定频道号
    private static final int QUALITY = 1;  // 高清抓拍

    @Autowired
    private YingShiTokenService yingShiTokenService;  // 引入 Token 服务

    public String captureImage() {
        // 使用 YingShiTokenService 获取 token
        String accessToken = yingShiTokenService.getAccessToken();  // 获取 accessToken

        RestTemplate restTemplate = new RestTemplate();

        // 设置请求参数
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("accessToken", accessToken);  // 使用通过 YingShiTokenService 获取的 accessToken
        body.add("deviceSerial", DEVICE_SERIAL);  // 使用硬编码的 deviceSerial
        body.add("channelNo", String.valueOf(CHANNEL_NO));  // 使用硬编码的 channelNo
        body.add("quality", String.valueOf(QUALITY));  // 使用高清抓拍

        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        // 发送 POST 请求
        ResponseEntity<String> response = restTemplate.exchange(CAPTURE_URL, HttpMethod.POST, requestEntity, String.class);

        // 解析返回结果
        if (response.getStatusCode() == HttpStatus.OK) {
            try {
                // 解析响应
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readTree(response.getBody());

                if ("200".equals(jsonNode.get("code").asText())) {
                    // 获取图片URL
                    JsonNode dataNode = jsonNode.get("data");
                    return dataNode != null ? dataNode.get("picUrl").asText() : null;
                } else {
                    throw new RuntimeException("摄像头抓拍失败，返回码：" + jsonNode.get("code").asText());
                }
            } catch (Exception e) {
                throw new RuntimeException("解析抓拍响应失败", e);
            }
        } else {
            throw new RuntimeException("调用抓拍接口失败，状态码：" + response.getStatusCode());
        }
    }
}
